package com.tianyi.userRegion;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.tianyi.comUser.ComUserService;
import com.tianyi.dao.entity.comUser.ComUser;
import com.tianyi.dao.entity.userRegion.UserRegion;
import com.tianyi.dao.entity.userRegion.UserRegionExample;
import com.tianyi.dao.mapper.UserRegionMapper;
import com.tianyi.lib.model.WebResult;
import com.tianyi.lib.req.UserAddrReq;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 用户收获地址
 *
 * @author cuixuhui
 * @date 2020/05/08
 */
@Service
public class UserRegionService {

    private static final Logger logger = LoggerFactory.getLogger(UserRegionService.class);

    @Autowired
    private UserRegionMapper userRegionMapper;
    @Autowired
    private ComUserService comUserService;

    public WebResult<String> preCheck(UserAddrReq req){

        if (StringUtils.isBlank(req.getConsignee())){
            return WebResult.error("收件人姓名为空");
        }
        if (StringUtils.isBlank(req.getPhone())){
            return WebResult.error("联系电话为空");
        }
        if (StringUtils.isBlank(req.getRegion())){
            return WebResult.error("所在地区为空");
        }
        if (StringUtils.isBlank(req.getArea())){
            return WebResult.error("详细地址为空");
        }
        if (StringUtils.isBlank(req.getOpenId())){
            return WebResult.error("小程序id为空");
        }
        return WebResult.ok("ok");
    }

    /**
     *
     * @param req       请求
     * @param region    地址记录
     * @param userId    用户id
     * @return
     */
    public UserRegion gentUserRegionByReq(UserAddrReq req, UserRegion region, Long userId){

        region.setGmtModified(new Date());
        region.setConsignee(req.getConsignee());
        region.setPhone(req.getPhone());
        region.setRegion(req.getRegion());
        region.setArea(req.getArea());
        region.setComUserId(userId);
        region.setIsDef(req.isDef());
        return region;
    }

    /**
     * 新增用户地址
     * @param req
     * @return
     */
    public WebResult<String> addAddress(UserAddrReq req){

        WebResult<String> preCheck = preCheck(req);
        if (!preCheck.isSuccess()){
            return preCheck;
        }
        ComUser comUser = comUserService.queryComUserByIdOrOpenId(req.getId(), req.getOpenId());
        if (Objects.isNull(comUser)){
            return WebResult.error("用户未登陆");
        }

        //将已有到默认改成普通
        if (req.isDef()){
            update2unDef(comUser.getId());
        }

        UserRegion region = new UserRegion();
        region.setGmtCreate(new Date());
        region.setGmtModified(new Date());

        region = gentUserRegionByReq(req, region, comUser.getId());

        int i = userRegionMapper.insert(region);
        return  WebResult.ok("success");
    }

    /**
     * 将用户所有的id设置成非默认
     * @param userId
     */
    public void update2unDef(Long userId){

        UserRegionExample example = new UserRegionExample();
        example.createCriteria().andIsDefEqualTo(Boolean.TRUE).andComUserIdEqualTo(userId);

        List<UserRegion> userRegions = userRegionMapper.selectByExample(example);

        if (CollectionUtils.isEmpty(userRegions)){
            return;
        }
        List<UserRegion> regionList = userRegions.stream().map(ret -> {
            ret.setIsDef(Boolean.FALSE);
            ret.setGmtModified(new Date());
            return ret;
        }).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(regionList)){
            return;
        }
        userRegionMapper.batchUpdateByPrimaryKey(regionList);
    }

    /**
     * 更新用户地址
     * @param req
     * @return
     */
    public WebResult<String> updateAddress(UserAddrReq req) {

        if (Objects.isNull(req.getId())){
            return WebResult.error("id 不能为空");
        }
        WebResult<String> preCheck = preCheck(req);
        if (!preCheck.isSuccess()){
            return preCheck;
        }
        ComUser comUser = comUserService.queryComUserByIdOrOpenId(null, req.getOpenId());
        if (Objects.isNull(comUser)){
            return WebResult.error("用户未登陆");
        }
        UserRegion userRegion = userRegionMapper.selectByPrimaryKey(req.getId());
        if (Objects.isNull(userRegion)){
            return WebResult.error("地址不存在");
        }
        //将已有到默认改成普通
        if (req.isDef()){
            update2unDef(comUser.getId());
        }

        userRegion = gentUserRegionByReq(req, userRegion, comUser.getId());

        int i = userRegionMapper.updateByPrimaryKeySelective(userRegion);
        return  WebResult.ok("success");
    }

    /**
     * 根据id获取用户地址
     * @param req
     * @return
     */
    public WebResult<UserRegion> queryByRecordId(UserAddrReq req) {

        if (Objects.isNull(req.getId())){
            return WebResult.error("id 不能为空");
        }
        if (StringUtils.isBlank(req.getOpenId())){
            return WebResult.error("小程序id为空");
        }
        ComUser comUser = comUserService.queryComUserByIdOrOpenId(req.getId(), req.getOpenId());
        if (Objects.isNull(comUser)){
            return WebResult.error("用户未登陆");
        }
        UserRegion userRegion = userRegionMapper.selectByPrimaryKey(req.getId());
        if (Objects.isNull(userRegion)){
            return WebResult.error("地址不存在");
        }

        return WebResult.ok(userRegion);
    }

    /**
     * 获取用户地址分页
     * @param req
     * @return
     */
    public WebResult<PageInfo<UserRegion>> queryAddress(UserAddrReq req) {

        if (StringUtils.isBlank(req.getOpenId()) && Objects.isNull(req.getId())){
            return WebResult.error("小程序id为空");
        }
        ComUser comUser = comUserService.queryComUserByIdOrOpenId(req.getId(), req.getOpenId());
        if (Objects.isNull(comUser)){
            return WebResult.error("用户未登陆");
        }

        UserRegionExample example = new UserRegionExample();
        example.setOrderByClause("is_def DESC, id DESC");
        example.createCriteria().andComUserIdEqualTo(comUser.getId());
        Page<UserRegion> userRegions = userRegionMapper.selectByExample(example, new RowBounds(req.getPageNo(), 20));
        PageInfo<UserRegion> userRegionPageInfo = userRegions.toPageInfo();

        return WebResult.ok(userRegionPageInfo);
    }
}
